package com.gm.commonlib.util.jsonUtils;

import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Iterator;

/**
 * 解析json
 *
 * @author hck
 */
public class JsonUtils {

    private static Gson gson;

    private static Gson getMapper() {
        if (gson == null) {
            gson = new Gson();
        }
        return gson;
    }

    public static <T> T parse(String json, Class<T> clazz)  {
        return getMapper().fromJson(json,clazz);
    }
    public static <T> T parse(String json, Type type )  {
        return getMapper().fromJson(json,type);
    }


    public static String toString(Object object)  {
        return getMapper().toJson(object);
    }

    public static void parseJsonToMap(String json, HashMap<String, Object> objectMap) {
        if (json == null) {
            return;
        }
        try {
            JSONObject jsonObject = new JSONObject(json);
            Iterator<String> keyset = jsonObject.keys();
            while (keyset.hasNext()) {
                String key = keyset.next();
                objectMap.put(key, jsonObject.get(key));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
